package com.zsrt.javaweb.bbu.book.dao.impl;

import org.springframework.jdbc.core.JdbcTemplate;

import com.zsrt.javaweb.bbu.book.dao.BookShopDao;
import com.zsrt.javaweb.bbu.book.exception.BookStockException;
import com.zsrt.javaweb.bbu.book.exception.UserAccountException;


/**
 * mysql不支持检查约束
 * @author scott
 *
 */
public class BookShopDaoImpl implements BookShopDao {

	private JdbcTemplate jdbcTemplate;
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	/**
	 * 根据书号查询书的价格 book
	 */
	@Override
	public int findBookPriceByIsbn(int isbn) {
		String sql="select price from book where isbn=?";
		int price = jdbcTemplate.queryForObject(sql, Integer.class, isbn);
		return price;
	}

	/**
	 * 更新书的库存 book_stock 每次只能买一本书  每次使得书的数量减少一本。
	 */
	@Override
	public int updateBookStock(int isbn) {
		
		//库存必须最少有一本书才能借书 否则巧妇难为无米之炊
		String query ="select stock from book_stock where isbn=?";
		int stock = jdbcTemplate.queryForObject(query, Integer.class,isbn);
		
		if(stock>=1){
			String sql="update book_stock set stock=stock-1 where isbn=?";
			//影响的记录的条数
			int count = jdbcTemplate.update(sql, isbn);
			System.out.println("isbn为"+isbn+"库存数减"+count+"成功...");
			return count;
		}else{
			throw new BookStockException(isbn+"库存不足,无法订购...");
		}
	}

	/**
	 * 修改用户的账户余额 account  新的余额=balance-书的价格price  [因为一次只能购买一本书]ßßß
	 */
	@Override
	public int updateUserAccount(String username, int price) {
		//必须验证余额是否>=price
		String query ="select balance from account where username=?";
		int balance = jdbcTemplate.queryForObject(query, Integer.class,username);
		if(balance < price){
			System.out.println(username+"账户减少"+price+"失败...");
			throw new UserAccountException("账户余额不足,无法订购...");
		}
				
		String sql="update account set balance=balance-? where username=?";
		//影响的记录的条数
		int count = jdbcTemplate.update(sql, price,username);
		System.out.println(username+"账户减少"+price+"成功...");
		return count;

	}

}
